package Client;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.UnknownHostException;

public class Client implements Runnable {
	private String inline = "";
	private Socket socket;
	private DataOutputStream out;
	private BufferedReader in;
	private CommandHandler commandHandler;
	private boolean connected = false;
	private boolean loggedIn = false;
	private boolean waiting = false;

	public Client(String host, int port) {
		try {
			socket = new Socket(host, port);
			out = new DataOutputStream(socket.getOutputStream());
			in = new BufferedReader(new InputStreamReader(
					socket.getInputStream()));
			commandHandler = new CommandHandler( this );
		} catch (UnknownHostException e) {
			System.err.println("Don't know about host: " + host);
		} catch (IOException e) {
			System.err.println("Couldn't get I/O for the connection to: "
					+ host);
		}
	}

	private void close() {
		try {
			out.close();
			in.close();
			socket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	@Override
	public void run() {
		if (socket == null || out == null || in == null) {
			System.err.println("Something is wrong. One variable is null.");
			return;
		}
		connected = validateServer();
		try {
			while ( connected ) {
				inline = in.readLine();
				if (inline != null && !inline.isEmpty()) {
					commandHandler.handle( inline );
				}
			}
		} catch (UnknownHostException e) {
			System.err.println("Trying to connect to unknown host: " + e);
		} catch (IOException e) {
			System.err.println("IOException:  " + e);
		} finally {
			close();
		}
	}
	
	public void send(String outline) {
		try {
			out.writeBytes(outline + "\n");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private boolean validateServer() {
		try {
			while (true) {
				out.writeBytes("210 ATM4286 9876" + "\n");
				inline = in.readLine();
				if( inline != null && !inline.isEmpty() ){
					if( inline.equals("310 Access_granted BNK5397") ){
						out.writeBytes("OK" + "\n");
						return true;
					} else {
						out.writeBytes("666 exit"); 
						return false;
					}
				}
			}
		} catch ( Exception e ){
			e.printStackTrace();
		}
		return false;
	}
	public CommandHandler getCommandHandler(){
		return commandHandler;
	}

	public boolean hasLoggedIn() {
		return loggedIn;
	}
	
	public void setLoggedIn( boolean logged ){
		loggedIn = logged;
	}

	public void setWaiting(boolean b) {
		waiting = b;
	}

	public boolean getWaiting() {
		return waiting;
	}


}
